package app

import (
	"gitee.com/zhucheer/orange/encrypt"
	"gitee.com/zhucheer/orange/session"
	"time"
)

// MiddlewareFunc defines a function to process middleware.
type MiddlewareFunc func(HandlerFunc) HandlerFunc

type HandlerFunc func(*Context) error

type MiddleWare interface {
	Func() MiddlewareFunc
}

// 翻转中间件，因执行时是从最外层函数开始，定义时需要从最后一个中间件开始定义
func reverseMiddleWare(middlewares []MiddleWare) []MiddleWare {
	length := len(middlewares)
	for i := 0; i < length/2; i++ {
		middlewares[length-1-i], middlewares[i] = middlewares[i], middlewares[length-1-i]
	}
	return middlewares
}

func startCsrfToken(session session.Store) string {
	csrfToken := getAppKey() + time.Now().String()
	csrfTokenMd5 := encrypt.Md5ToUpper(csrfToken)
	sessionKey := "CSRF-TOKEN"

	if token := session.Get(sessionKey); token != nil {
		return token.(string)
	}
	session.Set(sessionKey, csrfTokenMd5)

	return csrfTokenMd5
}

func checkCsrfToken(next HandlerFunc) HandlerFunc {
	return func(c *Context) error {
		tokenInHeader := c.request.Header.Get("CSRF-TOKEN")
		if c.request.Method == "POST" && tokenInHeader != c.CsrfToken {
			return c.ResponseWrite([]byte("csrf token verify error"))
		}
		return next(c)
	}
}
